import { Component, OnChanges, OnInit, ViewChild } from '@angular/core';
import { of } from 'rxjs/index';
import { catchError } from 'rxjs/operators';
import { PopService } from '../../../service/pop/pop.service';
import { SettingsService } from '@delon/theme';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { CommService } from '../../../service/comm/comm.service';

@Component({
  selector: 'pop-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['../../order/cart-list/cart-list.component.less'],
})
export class PopCartComponent implements OnInit {
  nodata = true;
  private list: Array<any>;
  // list: any = [];
  loading = false;
  currency = null;
  imgSuffix = '';
  defaultUrl = './assets/tmp/img/dummy.png';
  private total = 0;
  private totalExwPrice = 0;
  private totalCifPrice = 0;
  // imgSuffix = '';
  // defaultUrl = './assets/tmp/img/dummy.png';

  constructor(
    private popService: PopService,
    private setting: SettingsService,
    private comm: CommService,
    private msg: NzMessageService,
    private modalService: NzModalService,
  ) {}

  ngOnInit() {
    this.currency = this.setting.user.currency;
    this.imgSuffix = this.comm.getGoodsUrl();
    this.list = [];
    console.log('ngOnInit');
    this.load();
  }
  _onReuseInit() {
    this.load();
  }

  load(brand: string = '') {
    this.loading = true;
    this.popService
      .cartList()
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(res => {
        this.loading = false;
        if (res.status === 200) {
          this.list = res.data.rows;
          this.total = this.orderCount();
          this.calcTotalPrice();
          this.checkNoData();
        }
      });
  }

  orderCount() {
    let count = 0;
    for (let i = 0; i < this.list.length; i++) {
      count += this.list[i].qty;
    }
    return count;
  }

  calcTotalPrice() {
    this.totalExwPrice = 0;
    this.totalCifPrice = 0;
    for (let i = 0; i < this.list.length; i++) {
      this.totalExwPrice += this.list[i].exw;
      this.totalCifPrice += this.list[i].cif;
    }
    // for (const order of this.list) {
    //   this.totalExwPrice += order.qty * order.exw;
    //   this.totalCifPrice += order.qty * order.cif;
    // }
  }

  checkNoData() {
    const num = this.orderCount();
    if (num > 0) {
      this.nodata = false;
    } else {
      this.nodata = true;
    }
  }

  qtyChange(detail, order, val) {
    this.popService
      .modifyCart(detail.id, detail.brand, val)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(res => {
        if (res.status === 200 || res.code === 200) {
          this.calcOrderQty(order);
          this.calcTotalPrice();
          this.total = this.orderCount();
        } else {
          this.msg.error(res.message);
        }
      });
  }

  /**
   *  重新计算总数
   * @param o
   * @returns {number}
   */
  calcOrderQty(o): number {
    o.qty = 0;
    o.exw = 0;
    o.cif = 0;
    // 重新计算总数
    for (let i = 0; i < o.detail.length; i++) {
      o.qty += +o.detail[i].qty;
      o.exw += o.detail[i].qty * o.detail[i].exw;
      o.cif += o.detail[i].qty * o.detail[i].cif;
    }
    return o.qty;
  }

  /**
   * 删除购物车明细
   * @param detail
   * @param order
   */
  remove(detail, order, list) {
    this.showDeleteConfirm(
      'The item will be deleted!',
      () => {
        this.loading = true;
        this.popService
          .delByPopId(detail.id)
          .pipe(catchError(err => of(err)))
          .subscribe(data => {
            this.loading = false;
            if (data.status === 200) {
              this.msg.success('The item has been deleted');
              const arr = order.detail.slice();
              // 删除明细
              if (order.detail.length === 1) {
                list.splice(
                  list.findIndex(obj => obj.brand === order.brand),
                  1,
                );
              } else {
                arr.splice(arr.findIndex(obj => obj.id === detail.id), 1);
              }
              order.detail = arr;
              // 重新计算该订单的明细数
              this.calcOrderQty(order);
              this.total = this.orderCount();
              // 重新计算总金额
              this.calcTotalPrice();
              this.checkNoData();
            } else {
              this.msg.error(data.message);
            }
          });
      },
      () => {},
    );
  }

  /**
   * 按品牌批量删除订单
   * @param order
   * @param list
   */
  removeHead(order, list) {
    this.showDeleteConfirm(
      'The cart will be deleted!',
      () => {
        this.loading = true;
        this.popService
          .delByBrand(order.brand)
          .pipe(catchError(err => of(err)))
          .subscribe(data => {
            this.loading = false;
            if (data.status === 200) {
              this.msg.success('The cart has been deleted');
              // 删除明细
              list.splice(list.findIndex(obj => obj.brand === order.brand), 1);
              // 重新计算该订单的明细数
              this.total = this.orderCount();
              // 重新计算总金额
              this.calcTotalPrice();
              this.checkNoData();
            } else {
              this.msg.error(data.message);
            }
          });
      },
      () => {},
    );
  }

  /**
   * 订单提交
   * @param order
   */
  sumbitCart(order) {
    this.modalService.confirm({
      nzTitle: 'Are you sure?',
      nzContent: '<b style="color: red;">The order will be submit</b>',
      nzOkText: 'Yes',
      nzOkType: 'warning',
      nzOnOk: () => {
        this.loading = true;
        this.popService
          .creatOrderNoBrand()
          .pipe(
            catchError(err => {
              return of(err);
            }),
          )
          .subscribe(data => {
            this.loading = false;
            if (data.status === 200) {
              this.msg.success('success');
              // 删除明细
              this.list.splice(
                this.list.findIndex(obj => obj.brand === order.brand),
                1,
              );
              // 重新计算该订单的明细数
              this.total = this.orderCount();
              // 重新计算总金额
              this.calcTotalPrice();
              this.checkNoData();
            } else {
              this.msg.error(data.message);
            }
          });
      },
      nzCancelText: 'No',
      nzOnCancel: () => {},
    });
  }

  showDeleteConfirm(content, okFunc, cancelFunc): void {
    this.modalService.confirm({
      nzTitle: 'Are you sure?',
      nzContent: '<b style="color: red;">' + content + '</b>',
      nzOkText: 'Yes',
      nzOkType: 'danger',
      nzOnOk: okFunc,
      nzCancelText: 'No',
      nzOnCancel: cancelFunc,
    });
  }
}
